package com.xff.Controller;

import com.xff.Utils.MyDate;
import com.xff.bean.*;
import com.xff.dao.*;
import org.apache.coyote.Response;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@Controller
public class BookController {

    @ResponseBody
    @GetMapping("/img_download")
    public  byte[] down(HttpServletRequest request) throws Exception {

        String imgurl=request.getParameter("imgurl");
        FastDFSClient fdfs = new FastDFSClient();
        byte[] bytes = fdfs.download_bytes(imgurl);
       // String result = fdfs.uploadFile(bytes);

        /*group1/M00/00/00/wKjoDF-wXheAdQvOAAAFu4B1Pf83954794*/
        /*http://192.168.232.12:8888/group1/M00/00/00/wKjoDF-wXheAdQvOAAAFu4B1Pf83954794*/


        /*ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);*/
        return bytes;
    }
    @ResponseBody
    @GetMapping("/img_downloadbyid")
    public  byte[] downbyid(HttpServletRequest request) throws Exception {

        int bid=Integer.parseInt(request.getParameter("bid"));
        String imgurl=new BookDao().get_Bookimgurl(bid);
        FastDFSClient fdfs = new FastDFSClient();
        byte[] bytes = fdfs.download_bytes(imgurl);
        return bytes;
    }

    @PostMapping("/AddBookServlet")
    public String AddBookServlet(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestPart("file")MultipartFile file) throws Exception {
        if(session.getAttribute("status")!=null&&(int)session.getAttribute("status")==2) {
        String card = request.getParameter("card");
        String name = request.getParameter("name");
        String type = request.getParameter("type");
        String autho = request.getParameter("autho");
        //出版社
        String press = request.getParameter("press");
        String introduction = request.getParameter("introduction");
        int num = Integer.parseInt(request.getParameter("num"));
        int subscribenum=Integer.parseInt(request.getParameter("subscribenum"));
        int price = Integer.parseInt(request.getParameter("price"));

        byte[] buffer = file.getBytes();
        String imgurl=null;
        if(buffer.length!=0){
            FastDFSClient fdfs = new FastDFSClient();
            imgurl = fdfs.uploadFile(buffer,"jpg");
        }

         BookDao bookdao = new BookDao();
        //调用函数，存入图书
        bookdao.addBook(card, name, type, autho, press, num,subscribenum,imgurl,introduction,price);
        return "redirect:/admin_book";}
        else {
            return "redirect:/login";
        }
    }

    @RequestMapping("/DeleteServlet")
    public String DeleteServlet(HttpServletRequest request,HttpSession session) throws Exception {
        if(session.getAttribute("status")!=null&&(int)session.getAttribute("status")==2) {
            int bid = Integer.parseInt(request.getParameter("bid"));
            BookDao bookdao = new BookDao();
            String imgurl=bookdao.get_Bookimgurl(bid);
            FastDFSClient fdfs = new FastDFSClient();
            if(imgurl!=null)
                fdfs.delete_file(imgurl);
            bookdao.deleteBook(bid);
            return "redirect:/admin_book";
        }
        else {
            return "redirect:/login";
        }
    }

    @PostMapping("/UpdateBookServlet")
    public  String UpdateBookServlet(HttpServletRequest request,HttpSession session,@RequestPart("file")MultipartFile file) throws Exception {
        if(session.getAttribute("status")!=null&&(int)session.getAttribute("status")==2) {
            String card = request.getParameter("card");
            String name = request.getParameter("name");
            String type = request.getParameter("type");
            String autho = request.getParameter("autho");
            String press = request.getParameter("press");
            //Integer 类：parseInt() 方法用于将字符串参数作为有符号的十进制整数进行解析
            int num = Integer.parseInt(request.getParameter("num"));
            int bid = Integer.parseInt(request.getParameter("updatebid"));
            int subscribenum=Integer.parseInt(request.getParameter("subscribenum"));
            int price = Integer.parseInt(request.getParameter("price"));

            BookDao bookdao = new BookDao();
            byte[] buffer = file.getBytes();
            String imgurl=bookdao.get_Bookimgurl(bid);
            FastDFSClient fdfs = new FastDFSClient();
            if(imgurl!=null&&imgurl.length()!=0&&buffer.length!=0)
                fdfs.delete_file(imgurl);

            String nowimgurl=imgurl;
            if(buffer.length!=0){

                nowimgurl = fdfs.uploadFile(buffer,"jpg");
            }


            bookdao.updateBook(bid, card, name, type, autho, press, num,subscribenum,nowimgurl,price);
            return "redirect:/admin_book";
        }
        else {
            return "redirect:/login";
        }
    }

    @RequestMapping("/BorrowServlet")
    public  String BorrowServlet(HttpServletRequest request,HttpSession session){
        if(session.getAttribute("aid")!=null){
            BookDao bookdao = new BookDao();
            //为了区分借书和还书的功能，设置tip，tip为1，表示借书
            if(request.getParameter("tip")==null||request.getParameter("show")==null)
                return "redirect:/login";
            if(request.getParameter("hid")!=null||request.getParameter("bid")!=null){
                int tip = Integer.parseInt(request.getParameter("tip"));
                if (tip == 1) {
                    //获取图书ID
                    int bid = Integer.parseInt(request.getParameter("bid"));
                    AdminBean admin = new AdminBean();
                    //获取到存入session的aid读者id
                    String aid = (String)session.getAttribute("aid");
                    AdminDao admindao = new AdminDao();
                    //通过aid获取到读者信息
                    admin = admindao.get_AidInfo2(aid);
                    //将借阅记录存入数据库
                    bookdao.borrowBook(bid, admin);
                    return "redirect:/select";
                } else {
                    //还书功能，获取借阅记录的hid
                    int hid = Integer.parseInt(request.getParameter("hid"));
                    //还书在管理员和读者界面都有，为了区分，设置了show字段，show为1表示读者界面
                    int show = Integer.parseInt(request.getParameter("show"));
                    //调用还书函数，改变status字段
                    bookdao.borrowBook2(hid);
                    int bid =Integer.parseInt(request.getParameter("bid"));
                    int aid =Integer.parseInt(request.getParameter("aid"));

                    /*此书的可借阅数量+1*/
                    BookBean bookBean=bookdao.get_BookInfo(bid);
                    bookBean.setSubscribenum(bookBean.getSubscribenum()+1);
                    bookdao.updateBook(bookBean);

                    /*用户的当前借阅数量-1*/
                    AdminDao adminDao=new AdminDao();
                    AdminBean adminBean=adminDao.get_AidInfo2(aid+"");
                    adminBean.setBorrowing_num(adminBean.getBorrowing_num()-1);
                    adminDao.updateUser(adminBean);

                    if (show==1) {
                        return "redirect:/borrow";
                    } else {
                        return "redirect:/admin_borrow";
                    }
                }
            }
            return "redirect:/login";
        }
        else
            return "redirect:/login";
    }

    /*
    * 管理员挂失图书
    * */
    @RequestMapping("/LoseBookServlet")
    public  String LoseBookServlet(HttpServletRequest request,HttpSession session){
        if(session.getAttribute("status")!=null&&(int)session.getAttribute("status")==2) {
            int hid =Integer.parseInt(request.getParameter("hid"));
            int bid =Integer.parseInt(request.getParameter("bid"));
            int aid =Integer.parseInt(request.getParameter("aid"));
            BookDao bookDao=new BookDao();
            BookBean bookBean=bookDao.get_BookInfo(bid);
            /*将图书总数-1*/
            if(bookBean.getNum()==bookBean.getSubscribenum()){
                bookBean.setSubscribenum(bookBean.getSubscribenum()-1);
                bookBean.setNum(bookBean.getNum()-1);
            }else {
                bookBean.setNum(bookBean.getNum()-1);
            }
            bookDao.updateBook(bookBean);

             /*用户的当前借阅数量-1*/
            AdminDao adminDao=new AdminDao();
            AdminBean adminBean=adminDao.get_AidInfo2(aid+"");
            adminBean.setBorrowing_num(adminBean.getBorrowing_num()-1);
            adminDao.updateUser(adminBean);

            /*
            * 添加挂失、罚款信息
            * */
            int price=bookBean.getPrice();
            bookDao.losebook(hid,price*2);


            return "admin_borrow";
        }
        else
            return "redirect:/login";
    }

    @PostMapping("/SelectServlet")
    public  String SelectServlet(HttpServletRequest request,HttpSession session){
        if(session.getAttribute("aid")!=null){
            //因为在管理员界面和读者界面都有查找功能，为了将查找的结果返回正确的页面，设置了tip，tip=1表示管理员界面
            int tip = Integer.parseInt(request.getParameter("tip"));
            System.out.println(tip);
            String name = request.getParameter("name");
            BookDao bookdao = new BookDao();
            ArrayList<BookBean> data = bookdao.getLikeList(name);
            //将获取的结果存入请求中
            request.setAttribute("data", data);
            //判断，转发界面
            if (tip == 1) {
                return "admin_book";
            } else {
                return "select";
            }
        }
        else
            return "redirect:/login";

    }

    @PostMapping("/SelectBorrowServlet")
    public  String SelectBorrowServlet(HttpServletRequest request,HttpSession session){
        if(session.getAttribute("status")!=null&&(int)session.getAttribute("status")==2) {
            int tip = Integer.parseInt(request.getParameter("tip"));
            String name = request.getParameter("name");
            ArrayList<HistoryBean> historyBeans= new BookDao().get_BorrowListInfo(tip,name,1,4);
            //将获取的结果存入请求中
            request.setAttribute("data", historyBeans);
            return "admin_borrow";
        }
        else {
            return "redirect:/login";
        }
    }


    @PostMapping("/SelectHistoryServlet")
    public  String SelectHistoryServlet(HttpServletRequest request,HttpSession session){
        if(session.getAttribute("status")!=null&&(int)session.getAttribute("status")==2) {
            int tip = Integer.parseInt(request.getParameter("tip"));
            String name = request.getParameter("name");
            ArrayList<HistoryBean> historyBeans= new BookDao().get_BorrowListInfo(tip,name,0,0);
            //将获取的结果存入请求中
            request.setAttribute("data", historyBeans);
            return "admin_history";
        }else {
            return "redirect:/login";
        }

    }

    @PostMapping("/SelectLossServlet")
    public  String SelectLossServlet(HttpServletRequest request,HttpSession session){
        if(session.getAttribute("status")!=null&&(int)session.getAttribute("status")==2) {
            int tip = Integer.parseInt(request.getParameter("tip"));
            String name = request.getParameter("name");
            ArrayList<HistoryBean> historyBeans= new BookDao().get_BorrowListInfo(tip,name,3,3);
            //将获取的结果存入请求中
            request.setAttribute("data", historyBeans);
            return "admin_loss";
        }
        else {
            return "redirect:/login";
        }
    }



    @ResponseBody
    @GetMapping("/selectbooks")
    public  ArrayList<BookBean> SelectServlet(HttpServletRequest request){
            String name = request.getParameter("name");
            BookDao bookdao = new BookDao();
            ArrayList<BookBean> data = bookdao.getLikeList(name);
            return data;

    }

    @ResponseBody
    @GetMapping("/borrowhistory")
    public ArrayList<HistoryBean> borrowhistory(HttpServletRequest request){
        String username = request.getParameter("username");
        int tip =Integer.parseInt(request.getParameter("tip"));

        ArrayList<HistoryBean> historyBeans=new BookDao().get_HisoryListInfo2(tip,username);
        return historyBeans;
    }

    @ResponseBody
    @GetMapping("/losebook")
    public String losebook(HttpServletRequest request){
        int hid =Integer.parseInt(request.getParameter("hid"));
        int bid =Integer.parseInt(request.getParameter("bid"));
        int aid =Integer.parseInt(request.getParameter("aid"));
        BookDao bookDao=new BookDao();
        BookBean bookBean=bookDao.get_BookInfo(bid);
        if(bookBean.getNum()==bookBean.getSubscribenum()){
            bookBean.setSubscribenum(bookBean.getSubscribenum()-1);
            bookBean.setNum(bookBean.getNum()-1);
        }else {
            bookBean.setNum(bookBean.getNum()-1);
        }
        bookDao.updateBook(bookBean);

        /*用户的当前借阅数量-1*/
        AdminDao adminDao=new AdminDao();
        AdminBean adminBean=adminDao.get_AidInfo2(aid+"");
        adminBean.setBorrowing_num(adminBean.getBorrowing_num()-1);
        adminDao.updateUser(adminBean);

        /*
            * 添加挂失、罚款信息
            * */
        int price=bookBean.getPrice();
        bookDao.losebook(hid,price*2);

        return ""+price*2;
    }

    @ResponseBody
    @GetMapping("/renewbook")
    public String renewbook(HttpServletRequest request) throws ParseException {
        int hid =Integer.parseInt(request.getParameter("hid"));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HistoryPenaltyBean bean=new BookDao().get_HistoryPenaltyListInfo3(hid);

        int aid=bean.getAid();
        long day=new AdminDao().get_AidInfo2(aid+"").getLend_num();

        String new_endtime=MyDate.plusDay(30,bean.getEndtime());
        BookDao bookDao=new BookDao();
        Date endtime=format.parse(bean.getEndtime());
        Date begintime=format.parse(bean.getBegintime());
        long g=day*24*60*60*1000;
        Date now=new Date();
        if((long)(endtime.getTime()-begintime.getTime())>g){//续借过的不能再续借

            return "fail";
        }
        if(endtime.getTime()>now.getTime()){//没超期
            bean.setEndtime(new_endtime);
            bookDao.updateHistoryPenalty(bean);
            return "ok";
        }
        if((now.getTime()-endtime.getTime())<30*24*60*60*1000) {//超期不足30天
                if(bean.getPenaltystatus()==2){//还没有交钱的
                    bean.setPenaltystatus(0);
                    bean.setStatus(1);
                    bean.setNopaid(0);
                    bean.setEndtime(new_endtime);
                    bookDao.updateHistoryPenalty(bean);
                    return "ok";
                }
                if(bean.getPenaltystatus()==1){//已经交费的
                    bean.setStatus(1);
                    bean.setEndtime(new_endtime);
                    bookDao.updateHistoryPenalty(bean);
                    return "ok";
                }

            }else {

            return "fail";
            }

        return "fail";
    }

    @ResponseBody
    @GetMapping("/SelectCollectBooks")
    public ArrayList<BookBean> SelectCollectBooks(HttpServletRequest request) {
       String bids = request.getParameter("bids");
        BookDao bookDao=new BookDao();
        String[] bid= bids.split("-");
        ArrayList<BookBean> bookBeans=new ArrayList<>();
        for (String s : bid) {
            bookBeans.add(bookDao.get_BookInfo(Integer.parseInt(s)));
        }
        return bookBeans;
    }


}
